package com.situ.mall.admin.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.situ.mall.admin.pojo.dto.AdminLogin;
import com.situ.mall.admin.pojo.dto.ResetPasswordDTO;
import com.situ.mall.admin.pojo.query.AdminQuery;
import com.situ.mall.admin.service.IAdminService;
import com.situ.mall.common.util.CommonUtil;
import com.situ.mall.common.util.JwtUtil;
import com.situ.mall.common.util.Result;
import com.situ.mall.common.util.ThreadLocalUtil;
import com.situ.mall.pojo.entity.admin.Admin;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author z
 * @since 2024-10-09
 */
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private IAdminService adminService;
    @Autowired
    private RedisTemplate redisTemplate;
    @RequestMapping("/list")
    public Result list(AdminQuery adminQuery){
        //Ipage是什么？
        IPage<Admin> adminIPage = new Page<>(adminQuery.getPage(), adminQuery.getLimit());
        //QueryWrapper又是什么
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        //if the "name" attribute passed form the front end is not empty, then perform a fuzzy search
        queryWrapper.like(!ObjectUtils.isEmpty(adminQuery.getName()), "name", adminQuery.getName());
        //日期查询 between
        queryWrapper.between(!ObjectUtils.isEmpty(adminQuery.getBeginUpdateTime())&&!ObjectUtils.isEmpty(adminQuery.getEndUpdateTime()),
                "update_time", adminQuery.getBeginUpdateTime(), adminQuery.getEndUpdateTime());
        //我知道这是分页功能，但是里面封装了什么？
        adminService.page(adminIPage, queryWrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("total", adminIPage.getTotal());
        map.put("list", adminIPage.getRecords());
        return Result.ok(map);
    }
    @DeleteMapping("/deleteById/{id}")
    public Result deleteById(@PathVariable Integer id) {
        adminService.removeById(id);
        return Result.ok("删除成功");
    }
    @DeleteMapping("deleteAll/{ids}")
    public Result deleteAll(@PathVariable Integer[] ids){
        adminService.removeByIds(Arrays.asList(ids));
        return Result.ok("delete success");
    }
    @PostMapping("add")
    public Result add(@RequestBody Admin admin) {
        adminService.save(admin);
        return Result.ok("add success");
    }
    @PutMapping("/update")
    public Result update(@RequestBody Admin admin) {
        adminService.updateById(admin);
        return Result.ok("update success");
    }
    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        Admin admin = adminService.getById(id);
        return Result.ok(admin);
    }
    @PostMapping("/login")
    public Result login(@RequestBody AdminLogin adminLogin , HttpServletRequest request) {
        System.out.println("AdminController.login");
        //check the captcha before all option
        String captcha = (String) redisTemplate.opsForValue().get(CommonUtil.getCaptchaKey(request));
        if (StringUtils.isEmpty(captcha)) {
            return Result.error("验证码已失效");
        }
        if (!captcha.equalsIgnoreCase(adminLogin.getCaptcha())) {
            return Result.error("请输入正确验证码");
        }
        //The verification code verification was successful, and now the query statement is being executed.
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", adminLogin.getName());
        Admin loginAdmin = adminService.getOne(queryWrapper);
        if (loginAdmin == null) {
            return Result.error("用户名错误");
        }
        if(!adminLogin.getPassword().equals(loginAdmin.getPassword())) {
            return Result.error("wrong password");
        }
        //用户名和密码都正确
        //登录成功
        Map<String, Object> map = new HashMap<>();
        //为什么放的是id和name而不是password
        map.put("id", loginAdmin.getId());
        map.put("name", loginAdmin.getName());
        String token = JwtUtil.createToken(map);
        return Result.ok("登录成功", token);
    }
    @GetMapping("/adminInfo")
    public Result adminInfo(@RequestHeader(name = "Authorization") String token) {
        //1.take the token's data first
        Map<String, Object> map = JwtUtil.parseToken(token);
        //2.OK, The admin information already in the map, now use the "Query wrapper"
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        //It should be based on the ID, but let's assume that the username is unique
        queryWrapper.eq("name", map.get("name"));
        Admin admin = adminService.getOne(queryWrapper);
        return Result.ok(admin);
    }
    @PutMapping("/updateStatus")
    public Result updateStatus(Admin admin){
        adminService.updateById(admin);
        return Result.ok("修改成功");
    }
    @PutMapping("/resetPassword")
    public Result resetPassword(@RequestBody ResetPasswordDTO passwordDTO/*, @RequestHeader(name = "Authorization") String token*/){
        System.out.println("BlogController.resetPassword");
        //token是从请求头里拿到的,JwtUtil只是转换一下
        //Map<String, Object> map = JwtUtil.parseToken(token);
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        queryWrapper.eq("password",passwordDTO.getOldPassword());
        Admin admin = adminService.getOne(queryWrapper);
        if(admin == null){
            return Result.error("原密码错误");
        }
        UpdateWrapper<Admin> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id).set("password",passwordDTO.getNewPassword());
        adminService.update(updateWrapper);
        return Result.ok("更新成功");
    }

}

